﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace NewProcessGuarder.toolFunc
{
    public class Native
    {

        [System.Runtime.InteropServices.DllImport("ole32.dll")]
        public static extern void CoFreeUnusedLibraries();

        [System.Runtime.InteropServices.DllImport("user32")]
        public static extern int mouse_event(int dwflags, int dx, int dy, int cbuttons, int dwextrainfo);

        public static int mouseeventf_move = 0x0001;//移动鼠标
        public static int mouseeventf_leftdown = 0x0002;//模拟鼠标左键
        public static int mouseeventf_leftup = 0x0004;//左键按
        public static int mouseeventf_rightdown = 0x0008;
        public static int mouseeventf_rightup = 0x0010;
        public static int mouseeventf_middledown = 0x0020;
        public static int mouseeventf_middleup = 0x0040;
        public static int mouseeventf_absolute = 0x8000;//是否在用绝对坐标

        [System.Runtime.InteropServices.DllImport("user32")]
        public static extern bool SetCursorPos(int X, int Y);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern System.IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);

        [DllImport("user32.dll")]
        public static extern IntPtr GetWindow(IntPtr hWnd, uint nCmd);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowProc lpEnumFunc, IntPtr lParam);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassName(IntPtr hWnd, StringBuilder ClassName, int nMaxCount);

        /// <summary>
        /// Delegate for the EnumChildWindows method
        /// </summary>
        /// <param name="hWnd">Window handle</param>
        /// <param name="parameter">Caller-defined variable; we use it for a pointer to our list</param>
        /// <returns>True to continue enumerating, false to bail.</returns>
        public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);

        [DllImportAttribute("user32.dll")]
        public extern static IntPtr GetDC(IntPtr handle);

        [DllImportAttribute("user32.dll", ExactSpelling = true)]
        public extern static int ReleaseDC(IntPtr handle, IntPtr hDC);

        [DllImportAttribute("gdi32.dll")]
        public extern static IntPtr CreateCompatibleDC(IntPtr hDC);

        [DllImportAttribute("gdi32.dll")]
        public extern static bool DeleteDC(IntPtr hdc);

        [DllImportAttribute("gdi32.dll")]
        public extern static IntPtr SelectObject(IntPtr hDC, IntPtr hObject);

        [DllImportAttribute("gdi32.dll")]
        public extern static bool DeleteObject(IntPtr hObject);

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);

        [DllImport("User32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("User32.dll ")]
        public static extern int GetWindowText(IntPtr handle, StringBuilder text, int MaxLen);

        //public static int GetWindowText(IntPtr hwnd, StringBuilder buffer, int nMaxCount)
        //{
        //    string caption = string.Empty;
        //    IntPtr ptr = Marshal.StringToHGlobalAnsi(caption);
        //    Native.SendMessage(hwnd, Messages.WM_GETTEXT, new IntPtr(nMaxCount), ptr);
        //    caption = Marshal.PtrToStringAnsi(ptr);
        //    buffer.Append(caption);
        //    return caption.Length;
        //}


        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern bool SetWindowText(IntPtr hwnd, String lpString);

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);


        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern int SendTxtMessage(
            int hWnd, // handle to destination window 
            int Msg, // message 
            int wParam, // first message parameter 
            char[] lParam
        // int  lParam // second message parameter 
        );


        [DllImport("user32.dll")]
        public static extern bool IsWindowVisible(IntPtr hwnd);

        [DllImport("user32.dll")]
        static public extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        static public extern short GetKeyState(int nVirtKey);

        [DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
        public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

        [DllImport("user32.dll")]
        public static extern byte MapVirtualKey(int uCode, int uMapType);

        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        /// <summary>
        /// 得到parent窗体下的所有子窗体
        /// </summary>
        /// <param name="parent">父窗体</param>
        /// <param name="e">条件函数</param>
        /// <returns>满足条件的所有子窗体的列表</returns>
        public static List<IntPtr> GetChildWindows(IntPtr parent, Predicate<IntPtr> e)
        {
            List<IntPtr> result = new List<IntPtr>();
            GCHandle listHandle = GCHandle.Alloc(result);
            try
            {

                Native.EnumChildWindows(parent,
                    (handle, pointer) =>
                    {
                        GCHandle gch = GCHandle.FromIntPtr(pointer);
                        List<IntPtr> list = gch.Target as List<IntPtr>;
                        if (list == null)
                        {
                            throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
                        }
                        if (e(handle) == true)
                        {
                            list.Add(handle);
                        }
                        return true;
                    }
                    , GCHandle.ToIntPtr(listHandle));
            }
            finally
            {
                if (listHandle.IsAllocated)
                    listHandle.Free();
            }
            return result;
        }

        private static bool EnumWinodow(IntPtr hWhd, IntPtr IParam)
        {
            GCHandle gcChildhandlesList = GCHandle.FromIntPtr(IParam);
            if (gcChildhandlesList == null || gcChildhandlesList.Target == null)
                return false;

            List<IntPtr> childHandles = gcChildhandlesList.Target as List<IntPtr>;
            childHandles.Add(hWhd);
            return true;
        }

        public static List<IntPtr> GetChildWindows(IntPtr parent)
        {
            List<IntPtr> result = new List<IntPtr>();
            GCHandle listHandle = GCHandle.Alloc(result);
            IntPtr pointerChildHandlesList = GCHandle.ToIntPtr(listHandle);

            try
            {
                EnumWindowProc childProc = new EnumWindowProc(EnumWinodow);
                EnumChildWindows(parent, childProc, pointerChildHandlesList);
            }
            finally
            {
                listHandle.Free();
            }

            return result;
        }
    }
}
